import { buyNowApi, confirmOrderApi, submitOrderApi, createWeixinOrderApi } from '../../../api/order'
import { getOrderAddressApi } from '../../../api/address'
import { formatDate } from '../../../utils/tools';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    buyName: '', // 购买人名称
    buyPhone: '', // 购买人手机号
    deliveryDate: '请选择配送时间', // 期望送达日期
    remarks: '', // 客户备注
    totoalPrice: '', // 总价
    cartList: [], // 购物车列表
    isShowPopup: false, // 日期选项卡显示与隐藏
    minDate: new Date().getTime(), // 可选最小时间格式
    currentDate: new Date().getTime(), // 当期时间
    userAddress: {
      name: '',
      phone: '',
      address: '',
      fullAddress: '',
      id: ''
    }
  },

  handleShowPopup() {
    this.setData({
      isShowPopup: true
    })
  },

  /**
   * 点击日期timepicker取消按钮
   */
  hanleCancelTimePicker() {
    this.setData({
      isShowPopup: false
    })
  },
  /**
   * 关闭日期选项卡
   * 
   */
  onClose() {
    this.setData({
      isShowPopup: false
    })
  },

  handleConfirmTimePicker(e) {
    this.setData({
      deliveryDate: formatDate(e.detail),
      isShowPopup: false
    })
  },

  async getOrderAddress() {
    let name, phone, address, fullAddress, id;
    let userAddress = wx.getStorageSync('userAddress');
    if (userAddress) {
      userAddress = JSON.parse(userAddress);
      name = userAddress.name;
      phone = userAddress.phone;
      address = userAddress.address;
      fullAddress = userAddress.fullAddress;
      id = userAddress.id;
      wx.removeStorageSync('userAddress');
    } else {
      const res = await getOrderAddressApi();
      name = res.name;
      phone = res.phone;
      address = res.address;
      fullAddress = res.fullAddress;
      id = res.id;
    }
    
    this.setData({
      userAddress: {
        name,
        phone, address, fullAddress,
        id
      }
    })
  },

  async getCartList(options) {
    const { goodsId, blessing } = options;
    let res;
    if (goodsId) {
      res = await buyNowApi(goodsId, blessing);
    } else {
      res = await confirmOrderApi();
    }
    this.setData({
      cartList: res.cartVoList,
      totalPrice: res.totalAmount
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    /*  
      1. 商品详情-点击立即购买进来
        需要通过goodsId和blessing来获取要购买商品数据展示
        buyNowApi
      2. 购物车-点击去结算进来
        直接发送请求获取要购买商品数据展示
        confirmOrderApi
    */
    this.getCartList(options);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getOrderAddress();
  },

  // 去结算
  async submitOrder() {
    // 1. 发送请求给开发者服务器，生成服务器订单（携带参数：收件人信息、商品列表、价格等）
    const { buyName, buyPhone, cartList, deliveryDate, remarks, userAddress: { id } } = this.data;
    const orderNo = await submitOrderApi({
      userAddressId: id,
      buyName, buyPhone, cartList, deliveryDate, remarks
    });
    // 2. 发送请求给开发者服务器，生成微信支付订单（携带参数：上一步返回的订单号）
    const res = await createWeixinOrderApi(orderNo);
    /*
      nonceStr: "trfaV7Rvj0tURWmN" 随机字符串
      package: "prepay_id=wx150903131840246bb178a0131057280000" 微信支付的订单id
      paySign: "33CBB4B6E84BB74FDF4483065761F561" 签名
      signType: "MD5" 签名算法
      timeStamp: "1694739793270" 时间戳
    */
    // 3. 调用微信支付接口 wx.requestPayment ，发起微信支付（携带参数：上一步返回的4个参数）
    wx.requestPayment({
      ...res,
      success() {
        console.log('微信支付成功');
      },
      fail(err) {
        console.log('微信支付失败', err);
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})